package com.qiantu.phone.app;

import static java.lang.annotation.RetentionPolicy.SOURCE;

import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.IntDef;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.StringRes;

import com.gyf.immersionbar.ImmersionBar;
import com.hjq.bar.TitleBar;
import com.hjq.base.BaseActivity;
import com.hjq.base.BaseDialog;
import com.hjq.http.listener.OnHttpListener;
import com.qiantu.api.http.model.HttpData;
import com.qiantu.phone.R;
import com.qiantu.phone.action.TitleBarAction;
import com.qiantu.phone.action.ToastAction;
import com.qiantu.phone.glide.GlideApp;
import com.qiantu.phone.ui.dialog.ConfirmCancelHintDialog;
import com.qiantu.phone.ui.dialog.WaitDialog;

import java.lang.annotation.Retention;

import okhttp3.Call;

/**
 * author : Android 轮子哥F
 * github : https://github.com/getActivity/AndroidProject
 * time   : 2018/10/18
 * desc   : Activity 业务基类
 */
public abstract class AppActivity extends BaseActivity
        implements ToastAction, TitleBarAction, OnHttpListener<Object> {

    /**
     * 标题栏对象
     */
    private TitleBar mTitleBar;
    /**
     * 状态栏沉浸
     */
    private ImmersionBar mImmersionBar;

    /**
     * 加载对话框
     */
    private BaseDialog mDialog;
    private WaitDialog.Builder mWaitDialogBuilder;
    /**
     * 对话框数量
     */
    private int mDialogCount;

    /**
     * 当前加载对话框是否在显示中
     */
    public boolean isShowDialog() {
        return mDialog != null && mDialog.isShowing();
    }

    /**
     * 显示加载对话框
     */
    public void showDialog() {
        showDialog(null);
    }

    public void showDialog(String message) {
        if (isFinishing() || isDestroyed()) {
            return;
        }

        mDialogCount++;
        postDelayed(() -> {
            if (mDialogCount <= 0 || isFinishing() || isDestroyed()) {
                return;
            }

            if (mDialog == null) {
                mWaitDialogBuilder = new WaitDialog.Builder(this);
                mDialog = mWaitDialogBuilder.setCancelable(false)
                        .create();
            }
            mWaitDialogBuilder.setMessage(message);
            if (!mDialog.isShowing()) {
                mDialog.show();
            }
        }, 200);
    }

//    public void showDialog(String message) {
//        if (isFinishing() || isDestroyed()) {
//            return;
//        }
//        if (mDialog == null) {
//            mWaitDialogBuilder = new WaitDialog.Builder(this);
//            mDialog = mWaitDialogBuilder.setCancelable(false)
//                    .create();
//        }
//        mWaitDialogBuilder.setMessage(message);
//        if (!mDialog.isShowing()) {
//            mDialog.show();
//        }
//    }

    /**
     * 隐藏加载对话框
     */
    public void hideDialog() {
        if (isFinishing() || isDestroyed()) {
            return;
        }

        if (mDialogCount > 0) {
            mDialogCount--;
        }
        if (mDialogCount != 0 || mDialog == null || !mDialog.isShowing()) {
            return;
        }

        mDialog.dismiss();
    }

//    /**
//     * 隐藏加载对话框
//     */
//    public void hideDialog() {
//        if (isFinishing() || isDestroyed()) {
//            return;
//        }
//
//        if (mDialog == null || !mDialog.isShowing()) {
//            return;
//        }
//
//        mDialog.dismiss();
//    }

    @Override
    protected void initLayout() {
        setTheme(AppApplication.getInstance().getThemeResId());//获取主题ID
        getWindow().getDecorView().setBackgroundColor(AppApplication.getInstance().getThemeColor(R.attr.secondaryColor3));
        super.initLayout();
        if (getTitleBar() != null) {
            getTitleBar().setOnTitleBarListener(this);
        }

        // 初始化沉浸式状态栏
        if (isStatusBarEnabled()) {
            getStatusBarConfig().init();

            // 设置标题栏沉浸
            if (getTitleBar() != null) {
                ImmersionBar.setTitleBar(this, getTitleBar());
            }
        }
    }

    /**
     * 是否使用沉浸式状态栏
     */
    protected boolean isStatusBarEnabled() {
        return true;
    }

    /**
     * 状态栏字体深色模式
     */
    protected boolean isStatusBarDarkFont() {
        return AppApplication.getInstance().getThemeBoolean(R.attr.statusBarIsDarkFont);
    }

    /**
     * 获取状态栏沉浸的配置对象
     */
    @NonNull
    public ImmersionBar getStatusBarConfig() {
        if (mImmersionBar == null) {
            mImmersionBar = createStatusBarConfig();
        }
        return mImmersionBar;
    }

    /**
     * 初始化沉浸式状态栏
     */
    @NonNull
    protected ImmersionBar createStatusBarConfig() {
        return ImmersionBar.with(this)
                // 默认状态栏字体颜色为黑色
                .statusBarDarkFont(isStatusBarDarkFont())
                // 指定导航栏背景颜色
                .navigationBarColorInt(AppApplication.getInstance().getThemeColor(R.attr.shapeSolidColor))
                // 状态栏字体和导航栏内容自动变色，必须指定状态栏颜色和导航栏颜色才可以自动变色
                .autoDarkModeEnable(true, 0.2f);
    }

    /**
     * 设置标题栏的标题
     */
    @Override
    public void setTitle(@StringRes int id) {
        setTitle(getString(id));
    }

    /**
     * 设置标题栏的标题
     */
    @Override
    public void setTitle(CharSequence title) {
        super.setTitle(title);
        if (getTitleBar() != null) {
            getTitleBar().setTitle(title);
        }
    }

    @Override
    @Nullable
    public TitleBar getTitleBar() {
        if (mTitleBar == null) {
            mTitleBar = obtainTitleBar(getContentView());
        }
        return mTitleBar;
    }

    @Override
    public void onLeftClick(View view) {
        onBackPressed();
    }

    @Override
    public void startActivityForResult(Intent intent, int requestCode, @Nullable Bundle options) {
        super.startActivityForResult(intent, requestCode, options);
//        overridePendingTransition(R.anim.right_in_activity, R.anim.right_out_activity);
    }

    @Override
    public void finish() {
        super.finish();
//        overridePendingTransition(R.anim.left_in_activity, R.anim.left_out_activity);
    }

    /**
     *
     */
    @Override
    public void onStart(Call call) {
        showDialog();
    }

    @Override
    public void onSucceed(Object result) {
        if (result instanceof HttpData) {
            //toast(((HttpData<?>) result).getMessage());
        }
    }

    @Override
    public void onFail(Exception e) {
        toast(e.getMessage());
    }

    @Override
    public void onEnd(Call call) {
        hideDialog();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (isShowDialog()) {
            hideDialog();
        }
        mDialog = null;
    }

//    public void updateIsLocalState(){
//        View localNetTip = findViewById(R.id.local_net_tip);
//        if (localNetTip!=null){
//            localNetTip.setVisibility(AppApplication.isLocalNet? View.VISIBLE: View.GONE);
//        }
//    }

    public void showConfirmCancelHintDialog(String tip, String leftText, String rightText, ConfirmCancelHintDialog.OnListener listener) {
        new ConfirmCancelHintDialog.Builder(this)
                .setListener(listener)
                .setLeftText(leftText)
                .setRightText(rightText)
                .setContent(tip)
                .show();
    }

    public void showConfirmCancelHintDialog(int iconResId,String title,String tip,String leftText,String rightText,ConfirmCancelHintDialog.OnListener listener){
        new ConfirmCancelHintDialog.Builder(this)
                .setListener(listener)
                .setLeftText(leftText)
                .setRightText(rightText)
                .setContent(tip)
                .setHint(title)
                .setHintIcon(iconResId)
                .show();
    }

    public void showConfirmCancelHintDialog(String title, String tip, String leftText, String rightText, String rightTopText, ConfirmCancelHintDialog.OnListener listener, ConfirmCancelHintDialog.OnRightTopListener rightTopListener){
        new ConfirmCancelHintDialog.Builder(this)
                .setListener(listener)
                .setRightTopListener(rightTopListener)
                .setLeftText(leftText)
                .setRightText(rightText)
                .setRightTopText(rightTopText)
                .setContent(tip)
                .setHint(title)
                .show();
    }

    /**
     * imageview绑定数据
     *
     * @param imageViewId imageviewId
     * @param resId       资源id
     */
    protected void setImageViewBind(int imageViewId, int resId) {
        GlideApp.with(getContext())
                .load(resId)
                .into((ImageView) findViewById(imageViewId));
    }

    protected void setImageViewBind(int imageViewId, Drawable drawable) {
        ((ImageView) findViewById(imageViewId)).setImageDrawable(drawable);
    }

    /**
     * imageview绑定数据
     *
     * @param imageViewId imageviewId
     * @param url         网络路径
     */
    protected void setImageViewBind(int imageViewId, String url) {
        GlideApp.with(getContext())
                .load(url)
                .into((ImageView) findViewById(imageViewId));
    }

    /**
     * textview绑定数据
     *
     * @param textviewId 文本控件id
     * @param resId      资源id
     */
    protected void setTextViewBind(int textviewId, int resId) {
        ((TextView) findViewById(textviewId)).setText(resId);
    }

    /**
     * textview绑定数据
     *
     * @param textviewId 文本控件id
     * @param resId      资源id
     * @param format     格式化数据 比如 %s个场景
     */
    protected void setTextViewBind(int textviewId, int resId, String... format) {
        ((TextView) findViewById(textviewId)).setText(String.format(getString(resId), (Object[]) format));
    }

    /**
     * textview绑定数据
     *
     * @param textviewId 文本控件id
     * @param text       文本
     * @param format     格式化数据 比如 %s个场景
     */
    protected void setTextViewBind(int textviewId, String text, String... format) {
        ((TextView) findViewById(textviewId)).setText(String.format(text, (Object[]) format));
    }


    @Retention(SOURCE)
    @IntDef({android.view.View.VISIBLE, android.view.View.INVISIBLE, android.view.View.GONE})
    public @interface Visibility {
    }

    /**
     * 设置View显示隐藏
     *
     * @param viewId     viewId
     * @param visibility 控制显示隐藏 View.GONE,
     */
    protected void setVisibilityBind(int viewId, @Visibility int visibility) {
        findViewById(viewId).setVisibility(visibility);
    }

    /**
     * 获取view显示状态
     * @param viewId viewId
     * @return 返回visibility
     */
    protected int getVisibilityBind(int viewId) {
        return findViewById(viewId).getVisibility();
    }

    public AppActivity getAppActivity(){
        return this;
    }
}